package com.android.djlmapp.base;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.android.djlmapp.R;
import com.android.djlmapp.application.MyApplication;
import com.android.djlmapp.tools.global.KeyBordUtils;
import com.android.djlmapp.tools.global.MyActivityManager;
import com.android.djlmapp.tools.global.TakePhotoUtils;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.android.djlmapp.tools.msg.MQGlideImageLoader4;
import com.android.readcard.eventbus.Event;
import com.android.readcard.eventbus.EventBusUtil;
import com.gyf.barlibrary.ImmersionBar;
import com.jph.takephoto.app.TakePhoto;
import com.jph.takephoto.app.TakePhotoImpl;
import com.jph.takephoto.model.InvokeParam;
import com.jph.takephoto.model.TContextWrap;
import com.jph.takephoto.model.TResult;
import com.jph.takephoto.permission.InvokeListener;
import com.jph.takephoto.permission.PermissionManager;
import com.jph.takephoto.permission.TakePhotoInvocationHandler;
import com.just.agentweb.AgentWeb;
import com.lzy.okgo.OkGo;
import com.meiqia.meiqiasdk.imageloader.MQImage;
import com.meiqia.meiqiasdk.util.MQConfig;
import com.meiqia.meiqiasdk.util.MQIntentBuilder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.HashMap;

import me.yokeyword.fragmentation.SupportActivity;


/**
 * BaseActivity创建
 * 1,全局初始化控件方法initView();
 * 2,全局初始化数据方法initData();
 * 3,全局等待对话框创建,显示,关闭   -------- 尚未创建
 * 4,全局Toast方法
 * 5,全局EventBus的初始化和注销     EventBus.getDefault().post(new MessageEvent());
 * 6,全局权限请求(传入请求权限,提示字符串)
 * 7,全局activity管理类(添加,移除,清空)
 * 8,统一的标题栏(方便管理返回事件和沉浸式标题栏)
 * 9,全局拍照,相册选择
 * 10,控件绑定(在需要的activity里面使用)  ButterKnife.bind(this);
 */
public abstract class BaseActivity extends SupportActivity implements TakePhoto.TakeResultListener, InvokeListener {
    public AgentWeb mAgentWeb;
    private Toast toast;

    public boolean isUseFinishAnimation = true;
    private long lastClickTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getTakePhoto().onCreate(savedInstanceState);
//        getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        initSet();
    }

    @Override
    protected void onResume() {
        super.onResume();

        // 跳转美洽
        ImageView ivTopKf = findViewById(R.id.iv_top_kf);
        if (ivTopKf != null && ivTopKf.getVisibility() == View.VISIBLE) {
            ivTopKf.setOnClickListener(v -> goToMeiQia());

        }
        // 关闭界面
        LinearLayout llTopBack = findViewById(R.id.ll_top_back);
        if (llTopBack != null && llTopBack.getVisibility() == View.VISIBLE) {
            llTopBack.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (isCallBack()) {
                        btnBack();
                    } else {
                        callBack();
                    }
                }
            });
        }
    }

    public void callBack() {

    }

    public void btnBack() {
        finish();
    }

    private void initSet() {
        // 防止软键盘影响布局
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // 保持屏幕常亮
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//禁止横竖屏切换

        MyActivityManager.getAppManager().addActivity(this); // 添加到管理类


        toast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);
        if (isRegisterEventBus()) {
            EventBusUtil.register(this); // 注册EventBus
        }
        // 沉浸式
        initImmersionBar(R.color.homeWhite);
    }

    public String getToken() {
        return UserInfoUtils.getUserInfoUtilsInstance().getToken();
    }

    public String getVersion() {
        return UserInfoUtils.getUserInfoUtilsInstance().getVersion();
    }

    /**
     * 沉浸式状态栏初始化
     */
    public void initImmersionBar(int color) {
        ImmersionBar.with(this)
                .keyboardEnable(true)
                .navigationBarWithKitkatEnable(false)
                .statusBarDarkFont(true)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色;
                .statusBarColor(color)
                .statusBarDarkFont(true, 1.0f)
                .init();
    }

    /**
     * 初始化控件
     */
    protected abstract void initView();

    /**
     * 初始化数据
     */
    protected abstract void initData();

    /**
     * 跳转美洽
     */
    public void goToMeiQia() {
        // 美恰客服需要的字段

        HashMap<String, String> clientInfo = new HashMap<>();
        clientInfo.put("name", UserInfoUtils.getUserInfoUtilsInstance().getUserName());
        clientInfo.put("用户类型", "店铺");
        clientInfo.put("tel", UserInfoUtils.getUserInfoUtilsInstance().getMobile());
        clientInfo.put("address", UserInfoUtils.getUserInfoUtilsInstance().getFaddress());
        clientInfo.put("上级代理商", UserInfoUtils.getUserInfoUtilsInstance().getAgent());

        MQImage.setImageLoader(new MQGlideImageLoader4()); // 如果使用的是 glide 4.x ,就得在启动美洽前加上这句
        MQConfig.ui.backArrowIconResId = R.mipmap.mq_ic_back;
        Intent intent = new MQIntentBuilder(BaseActivity.this)
                .setClientInfo(clientInfo)
                .setCustomizedId(MyApplication.getInstance().getRegistrationId())
                .build();
        startActivity(intent);
    }

    @Override
    public void startActivityForResult(Intent intent, int requestCode) {
        super.startActivityForResult(intent, requestCode);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
    }

    /**
     * 返回true默认返回上一页
     * 返回false 自己决定跳转
     *
     * @return
     */
    protected boolean isCallBack() {
        return true;
    }

    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(Event event) {
        // 重写此方法获取MessageEvent
    }

    /**
     * 显示自定义Toast
     *
     * @param message
     */
    public void showToast(String message) {
        if (getActivity() != null) {
            Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * @param str      吐司的内容
     * @param location toast显示的位置 Gravity.CENTER
     */
    public void showToast(String str, int location) {
        if (!TextUtils.isEmpty(str) && str != null) {
            toast.setText(str);
        }
        toast.setGravity(location, 0, 0);
        toast.show();
    }

    public Activity getActivity() {
        return this;
    }


    @Override
    public void finish() {
        super.finish();
        if (isUseFinishAnimation) {
            overridePendingTransition(R.anim.push_left_in, R.anim.push_right_out);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // 如果你的app可以横竖屏切换，并且适配4.4或者emui3手机请务必在onConfigurationChanged方法里添加这句话
        ImmersionBar.with(this).init();
    }

    @Override
    protected void onPause() {
        super.onPause();
        KeyBordUtils.showKeyboard(BaseActivity.this);
    }

    @Override
    protected void onDestroy() {
        if (mAgentWeb != null) {
            mAgentWeb.destroy();
        }
        if (isRegisterEventBus()) {
            EventBusUtil.unregister(this); // 注销EventBus
        }
        ImmersionBar.with(this).destroy();
        //取消所有请求
        OkGo.getInstance().cancelAll();
        MyActivityManager.getAppManager().finishActivity(getActivity()); // 从管理类移除
        super.onDestroy();
        //取消更新通知
        AllenVersionChecker.getInstance().cancelAllMission(this);
    }


    //==========================================拍照==========================================

    private TakePhoto takePhoto;
    private InvokeParam invokeParam;
    private boolean isTake = false;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        getTakePhoto().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 相册选择照片
    public void choosePhoto() {
        isTake = true;
        Uri imageUri = TakePhotoUtils.configCamer(takePhoto);
        takePhoto.onPickFromGallery();
    }

    /**
     * 拍照
     */
    public void takePhoto() {
        isTake = true;
        // 拍照配置
        Uri imageUri = TakePhotoUtils.configCamer(takePhoto);
        takePhoto.onPickFromCapture(imageUri);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        getTakePhoto().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }


    @Override
    public void takeSuccess(TResult result) {

    }

    @Override
    public void takeFail(TResult result, final String msg) {

    }

    @Override
    public void takeCancel() {
    }

    @Override
    public PermissionManager.TPermissionType invoke(InvokeParam invokeParam) {
        PermissionManager.TPermissionType type = PermissionManager.checkPermission(TContextWrap.of(this),
                invokeParam.getMethod());
        if (PermissionManager.TPermissionType.WAIT.equals(type)) {
            this.invokeParam = invokeParam;
        }
        return type;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //以下代码为处理Android6.0、7.0动态权限所需
        PermissionManager.TPermissionType type = PermissionManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionManager.handlePermissionsResult(this, type, invokeParam, this);

    }

    /**
     * 获取TakePhoto实例
     *
     * @return
     */
    public TakePhoto getTakePhoto() {
        if (takePhoto == null) {
            takePhoto = (TakePhoto) TakePhotoInvocationHandler.of(this).bind(new TakePhotoImpl(this, this));
        }
        return takePhoto;
    }


    //设置android app 的字体大小不受系统字体大小改变的影响
    @Override
    public Resources getResources() {
        Resources res = null;
        try {
            res = super.getResources();
            Configuration config = new Configuration();
            config.setToDefaults();
            res.updateConfiguration(config, res.getDisplayMetrics());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("项目异常", "--onLivenessSuccess----getResources------" + e.toString());
        }
        return res;
    }

}
